package com.nitty.cash.loop.ui.fragment

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.nitty.cash.loop.R
import com.nitty.cash.loop.common.CommonFragment
import com.nitty.cash.loop.configs.NittyApiUrl.addCommonParams
import com.nitty.cash.loop.databinding.UiPageProcessGeneralBinding
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.ui.activity.ProcessAct
import com.nitty.cash.loop.ui.adapter.ProcessGeneralAdapter
import com.nitty.cash.loop.ui.dialog.NittyBirthdayDialog
import com.nitty.cash.loop.ui.popupwindow.NittySelectPopupwindow
import com.nitty.cash.loop.utils.NittyDensityUtil
import com.nitty.cash.loop.utils.decoration.LinearSpacingItemDecoration
import com.nitty.cash.loop.utils.log.NittyLogger
import org.json.JSONObject

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/11/19 14:19
 * @Annotation：认证流程 - 通用
 */
class ProcessGeneralFragment(): CommonFragment() {
    lateinit var binding: UiPageProcessGeneralBinding
    private var stepItem: JSONObject? = null

    private var generalAdapter: ProcessGeneralAdapter? = null
    private var mSelectPosition = -1

    //出生日期选择
    private var birthdayDialog: NittyBirthdayDialog? = null

    constructor(data: JSONObject): this(){
        this.stepItem = data
    }

    override fun getNittyRootView(inflater: LayoutInflater): View {
        binding = UiPageProcessGeneralBinding.inflate(inflater)
        return binding.root
    }

    override fun initNittyView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#00000000"))
        initAuthStepListView()
    }

    override fun initNittyListener() {
        //下一步
        binding.authStepCommonNext.setOnClickListener {
            if (stepItem == null){
                return@setOnClickListener
            }
            if (!isAllowCommonSubmit()){
                showErrorTipsDialog(getString(R.string.dialog_tips_submit_error), stepItem!!.optString("stepTitle"))
                return@setOnClickListener
            }
            val params = JSONObject().addCommonParams().apply {
                put("xd304965bcd9478080", stepItem!!.optString("apiUrl").replace("/",""))
            }
            for (i in 0..<generalAdapter!!.itemCount){
                val item = generalAdapter!!.getItem(i)
                if (item.has("selectItem")){
                    val selectItem = item.optJSONObject("selectItem")
                    if (selectItem != null){
                        params.put(item.optString("paramName"),selectItem.optString("value"))
                    }
                }
            }
            NittyLogger.e(">>>>>>submit data >>>>>>>$params")
            val act = getAct() as ProcessAct
            act.onProcessSubmitAction(params)

            addEventPointRequestAction(String.format(NittyEventPointType.CLICK.NITTY_CLICK_STEP_XX_NEXT, stepItem!!.optString("stepTitle")),"")
        }
    }

    override fun loadNittyData() {
        val dataList = arrayListOf<JSONObject>()
        if (stepItem != null){
            addEventPointRequestAction(String.format(NittyEventPointType.PAGE.NITTY_PAGE_STEP_COMMON_XX_START,stepItem?.optString("stepTitle")),"")
            binding.imgGeneralType.setImageResource(stepItem!!.optInt("stepIcon"))
            binding.authStepTitle.text = stepItem?.optString("showTitle")

            val dataArray = stepItem?.optJSONArray("dataList")
            if (dataArray != null) {
                for (i in 0..<dataArray.length()){
                    dataList.add(dataArray.optJSONObject(i))
                }
            }
        }
        generalAdapter?.data = dataList
    }

    /**
     * 初始化Views
     */
    private fun initAuthStepListView(){
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.authStepCommonListView.layoutManager = layoutManager
        val topDecoration = NittyDensityUtil.dp2px(16f)
        binding.authStepCommonListView.addItemDecoration(LinearSpacingItemDecoration(0, 0, 0, topDecoration))
        generalAdapter = ProcessGeneralAdapter(binding.authStepCommonListView)
        binding.authStepCommonListView.adapter = generalAdapter
        binding.authStepCommonListView.itemAnimator = DefaultItemAnimator()
        generalAdapter!!.setOnItemChildClickListener { _, childView, position ->
            binding.root.clearFocus()
            mSelectPosition = position
            val item = generalAdapter!!.getItem(position)
            when (item.optString("action")) {
                "DATE_PICK" -> {//时间选择
                    showAuthStepCommonBirthDialog()
                }
                "SELECT" -> {//选择
                    val dataList = arrayListOf<JSONObject>()
                    val dataArray = item.optJSONArray("values")
                    if (dataArray != null) {
                        for (i in 0..<dataArray.length()) {
                            dataList.add(dataArray.optJSONObject(i))
                        }
                    }
                    showSelectPopupwindow(childView, dataList)
                }
            }
        }
    }

    /**
     * 选择选项
     */
    private fun showSelectPopupwindow(view: View,dataList: ArrayList<JSONObject>){
        val selectPopup = NittySelectPopupwindow(requireContext())
        selectPopup.setWindowWidth(view.width + NittyDensityUtil.dp2px(10f))
        selectPopup.setSelectItemListener(object : NittySelectPopupwindow.IItemClickListener {
            //完成
            override fun onConfirmAction(data: JSONObject?) {
                val item = generalAdapter!!.getItem(mSelectPosition)
                item.put("selectItem",data)
                generalAdapter!!.notifyItemChanged(mSelectPosition)

                if (data != null){
                    val subRemark = "${data!!.optString("value")}$$${data.optString("duration")}"
                    addEventPointRequestAction(String.format(NittyEventPointType.CLICK.NITTY_CLICK_STEP_XX_SELECT,item.optString("paramName")),subRemark)
                }
            }
            //关闭监听
            override fun onDismissListener() {
            }
        })
        selectPopup.show(view, binding.root)
        selectPopup.setBrandList(dataList)
    }

    /**
     * 选择出生日期
     */
    private fun showAuthStepCommonBirthDialog(){
        if (birthdayDialog == null){
            birthdayDialog = NittyBirthdayDialog(requireContext(),"",object : NittyBirthdayDialog.IDialogCallback{
                override fun completed(selectDate: JSONObject) {
                    //可根据需要自行截取数据显示
                    val item = generalAdapter!!.getItem(mSelectPosition)
                    val obj = JSONObject()
                    obj.put("title",selectDate.optString("showDate"))
                    obj.put("title_sw",selectDate.optString("showDate"))
                    obj.put("value",selectDate.optString("subDate"))
                    item.put("selectItem",obj)
                    generalAdapter!!.notifyItemChanged(mSelectPosition)

                    val subRemark = "${selectDate.optString("subDate")}$$${selectDate.optString("duration")}"
                    addEventPointRequestAction(String.format(NittyEventPointType.CLICK.NITTY_CLICK_STEP_XX_SELECT,item.optString("paramName")),subRemark)
                }
            })
        }
        birthdayDialog!!.show()
    }

    /**
     * 通用类型列表
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowCommonSubmit(): Boolean{
        //是否允许提交
        var isAllow = true
        for (i in 0..<generalAdapter!!.itemCount){
            val item = generalAdapter!!.getItem(i)
            //存在 isMust && isMust == ”NO“  非必填
            if (item.has("isMust") && item.optString("isMust") == "NO"){
                continue
            }
            //必填 && 没有内容 || 内容为空
            if (!item.has("selectItem") || item.optJSONObject("selectItem")?.optString("value")!!.isEmpty()){
                isAllow = false
                break
            }
        }
        return isAllow
    }

    override fun onStart() {
        super.onStart()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (stepItem != null){
            addEventPointRequestAction(String.format(NittyEventPointType.PAGE.NITTY_PAGE_STEP_COMMON_XX_END,stepItem!!.optString("stepTitle")),"")
        }
    }
}